/*
 * @(#) ViewHolder.java 2016-1-21
 * 
 * Copyright (c) 2010, HMI Technology. All Rights Reserved. HMI Technology. CONFIDENTIAL
 */
package com.webkitlib.util;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * ViewHodle 封装
 * 
 * @author 韩伟光
 * @version 1.0
 * @since 2016-1-21
 */
public class ViewHolder {

    private static ViewHolder holder;
    private SparseArray<View> mViews;
    public int mPosition;
    private View mConvertView;

    /**
     * @param context
     * @param parent
     * @param layoutId
     * @param position
     * @param convertView
     */
    public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
        this.mPosition = position;
        this.mViews = new SparseArray<View>();
        mConvertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
        mConvertView.setTag(this);
    }


    /**
     * 获取ViewHolder
     * 
     * @param context 上下文
     * @param convertView 主布局
     * @param parent ViewGroup
     * @param layoutId 要加载的资源
     * @param position 位置
     * @return
     */
    public static ViewHolder get(Context context, View convertView, ViewGroup parent, int layoutId,
                    int position) {
        if (holder == null) {
            return new ViewHolder(context, parent, layoutId, position);
        } else {
            holder = (ViewHolder) convertView.getTag();
            holder.mPosition = position;
            return holder;
        }
    }

    /**
     * 根据组件id获取view
     * 
     * @param viewId
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    public View getmConvertView() {
        return mConvertView;
    }

    public ViewHolder setText(int viewid, String text) {
        TextView tv = (TextView) getView(viewid);
        tv.setText(text);
        return this;
    }


}
